package com.example.kotlintest.net

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.kotlintest.bean.TouTiaoData


private const val PAGE_INDEX = 0

class NewsPagingSource(
    private val api: ApiService
) : PagingSource<Int, TouTiaoData.Result.Data>() {

    override fun getRefreshKey(state: PagingState<Int, TouTiaoData.Result.Data>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, TouTiaoData.Result.Data> {
        val page = params.key ?: PAGE_INDEX
        return try {
            val response = api.toutiaoInfo(page, 30, "6e79b1bb8572ab993a708ae97b60078e")
            val datas = response.result.data
            LoadResult.Page(
                data = datas,
                prevKey = if (page == PAGE_INDEX) null else page - 1,
                nextKey = page + 1,
            )
        } catch (exception: Exception) {
            LoadResult.Error(exception)
        }
    }

}